package com.haitaoit.chengquan.module.home.activity.forum;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.home.adapter.forum.ForumCenterImgAdapter;
import com.haitaoit.chengquan.module.home.adapter.forum.ForumDetailEvaAdapter;
import com.haitaoit.chengquan.module.home.model.ForumCenterModel;
import com.haitaoit.chengquan.module.home.model.ForumDetailEvaModel;
import com.haitaoit.chengquan.module.login.LoginActivity;
import com.haitaoit.chengquan.ui.equipment.activity.ShowPictureActivity;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DateTimeUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.CircleImageView;
import com.haitaoit.chengquan.view.MyGridView;
import com.haitaoit.chengquan.view.MyListView;
import com.haitaoit.chengquan.view.PullToRefreshBase;
import com.haitaoit.chengquan.view.PullToRefreshScrollView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ForumDetailActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener<ScrollView> {
    @ViewInject(R.id.pullrefreshscrollview)
    PullToRefreshScrollView pullrefreshscrollview;
    @ViewInject(R.id.input_eva)
    EditText                input_eva;

    private ScrollView   mScrollView;
    private LinearLayout null_information_layout;
    private MyListView   listView;
    private MyGridView   gridView;
    private TextView     forum_type, forum_title, forum_name, forum_time, forum_content, visit_count, reply;
    private CircleImageView center_img;


    private boolean isFrist = true;
    private int     page    = 1;
    private ForumCenterImgAdapter imgAdapter;
    private ForumDetailEvaAdapter evaAdapter;
    private String                forumId, faburenId;
    private ForumCenterModel model;
    private String type = "1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.pullrefreshscollview2);
        setTitle_V("帖子详情");
        setLeftShow(1, R.mipmap.left);
        setRightShow(1, R.mipmap.img39);
        backLeft_V();
        ViewUtils.inject(this);


        View view = LayoutInflater.from(this).inflate(R.layout.activity_forum_detail, null);
        null_information_layout = (LinearLayout) view.findViewById(R.id.null_information_layout);
        gridView = (MyGridView) view.findViewById(R.id.forum_gridview);
        listView = (MyListView) view.findViewById(R.id.scrollview_listview);
        forum_type = (TextView) view.findViewById(R.id.forum_type);
        center_img = (CircleImageView) view.findViewById(R.id.center_img);
        forum_title = (TextView) view.findViewById(R.id.forum_title);
        forum_name = (TextView) view.findViewById(R.id.forum_name);
        forum_time = (TextView) view.findViewById(R.id.forum_time);
        forum_content = (TextView) view.findViewById(R.id.forum_content);
        visit_count = (TextView) view.findViewById(R.id.visit_count);
        reply = (TextView) view.findViewById(R.id.reply);
        view.findViewById(R.id.forum_infoLL).setOnClickListener(listener);
        forum_title.setOnClickListener(listener);
        forum_content.setOnClickListener(listener);
        view.findViewById(R.id.forum_numll).setOnClickListener(listener);

        pullrefreshscrollview.setPullLoadEnabled(true);
        pullrefreshscrollview.setPullRefreshEnabled(false);
        pullrefreshscrollview.setOnRefreshListener(this);
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        mScrollView = pullrefreshscrollview.getRefreshableView();
        mScrollView.setFillViewport(true);
        mScrollView.setVerticalScrollBarEnabled(false);
        mScrollView.addView(view);

        imgAdapter = new ForumCenterImgAdapter(this);
        gridView.setAdapter(imgAdapter);
        imgAdapter.setBackCall(new BackCall() {
            @Override
            public void deal(int which, Object... obj) {
                String imageUri = (String) obj[0];
                switch (which) {
                    case R.id.icon:
                        Intent intent = new Intent();
                        intent.setClass(ForumDetailActivity.this, ShowPictureActivity.class);
                        intent.putExtra("image_uri",imageUri);
                        startActivity(intent);
                        break;
                }

                super.deal(which, obj);
            }
        });

        evaAdapter = new ForumDetailEvaAdapter(this);
        listView.setAdapter(evaAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (evaAdapter.getList().get(position).getName().contains("回复")) {
                    input_eva.setHint("对" + evaAdapter.getList().get(position).getName().split("回复")[0] + "评论：");
                } else {
                    input_eva.setHint("对" + evaAdapter.getList().get(position).getName() + "评论：");
                }
                input_eva.setText("");
                faburenId = evaAdapter.getList().get(position).getUser_id();
                type = "2";
            }
        });
        forumId = getIntent().getStringExtra("id");
        httpGetesther_model();
    }

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            input_eva.setHint("对帖子评论...");
            input_eva.setText("");
            faburenId = model.getUser_id();
            type = "1";
        }
    };

    @OnClick({R.id.right, R.id.send_message,})
    public void onClick(View v) {// 收起键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.right:

                intent.setClass(ForumDetailActivity.this, PostForumActivity.class);
                intent.putExtra("typeName", model.getClass_name());
                startActivity(intent);
                break;
            case R.id.send_message:
                if (PreferenceUtils.getPrefString("user_id", "").equals("")) {
                    intent.setClass(this, LoginActivity.class);
                    intent.putExtra("tag", "0");
                    startActivity(intent);
                } else if (input_eva.getText().toString().equals("")) {
                    ToastUtils.showToast("请输入内容！");
                } else {
                    httpGeteadd_esther_comments();
                }
                break;
        }
        super.onClick(v);
    }

    // 帖子详情信息
    private void httpGetesther_model() {
        TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("id", forumId));
        list.add(new NameValuePairSign("ip", tm.getDeviceId()));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("id", forumId);
        params.addQueryStringParameter("ip", tm.getDeviceId());
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getesther_model, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                try {
                    JSONObject json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            model = gson.fromJson(Response, ForumCenterModel.class);
                            faburenId = model.getUser_id();
                            forum_type.setText(model.getClass_name()+"版块");
                            ImageLoader.getInstance().displayImage(model.getHead_portrait(), center_img);
                            forum_name.setText(model.getName());
                            forum_time.setText(model.getAddtime());
                            SpannableString msp = new SpannableString(model.getClass_name() + " | " + model.getTitle());
                            msp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0,
                                    model.getClass_name().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);// 粗体
                            msp.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.app_color)), 0,
                                    model.getClass_name().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                            forum_title.setText(msp);
                            forum_content.setText(model.getContent());
                            visit_count.setText(model.getVisit_count());
                            reply.setText(model.getComments_count());

                            if (model.getImg_list() == null || model.getImg_list().size() == 0) {
                                gridView.setVisibility(View.GONE);
                            } else {
                                gridView.setVisibility(View.VISIBLE);
                                imgAdapter.setList(model.getImg_list());
                                imgAdapter.notifyDataSetChanged();
                            }
                            httpGetesther_comments_list();
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
                httpGetesther_comments_list();
            }
        });
    }

    // 帖子回复列表
    private void httpGetesther_comments_list() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("esther_id", forumId));
        list.add(new NameValuePairSign("page", page + ""));
        list.add(new NameValuePairSign("pagesize", Constant.PageSize));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("esther_id", forumId);
        params.addQueryStringParameter("page", page + "");
        params.addQueryStringParameter("pagesize", Constant.PageSize);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getesther_comments_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                List<ForumDetailEvaModel> new_list = new ArrayList<ForumDetailEvaModel>();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<ForumDetailEvaModel>();
                            break;
                        case 0:// 成功
                            new_list = gson.fromJson(Response,
                                    new TypeToken<List<ForumDetailEvaModel>>() {
                                    }.getType());
                            break;
                        case 2:// 暂无内容
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<ForumDetailEvaModel>();
                            break;
                    }
                    if (isFrist) {
                        if (isNullDate(new_list)) {
                            evaAdapter.setList(new_list);
                            evaAdapter.notifyDataSetChanged();
                        }
                        pullrefreshscrollview.onPullDownRefreshComplete();
                    } else {
                        List<ForumDetailEvaModel> allList = evaAdapter.getList();
                        allList.addAll(new_list);
                        evaAdapter.setList(allList);
                        evaAdapter.notifyDataSetChanged();
                        pullrefreshscrollview.onPullUpRefreshComplete();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 发送评论
    private void httpGeteadd_esther_comments() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("type", type));
        list.add(new NameValuePairSign("be_user_id", faburenId));
        list.add(new NameValuePairSign("esther_id", forumId));
        list.add(new NameValuePairSign("content", input_eva.getText().toString()));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("type", type);
        params.addQueryStringParameter("be_user_id", faburenId);
        params.addQueryStringParameter("esther_id", forumId);
        params.addQueryStringParameter("content", input_eva.getText().toString());
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Geteadd_esther_comments, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            reply.setText((Integer.valueOf(reply.getText().toString()) + 1) + "");
                            input_eva.setText("");
                            isFrist = true;
                            page = 1;
                            httpGetesther_comments_list();
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    /**
     * @tab 判断listview是否有值
     */
    private boolean isNullDate(List<ForumDetailEvaModel> rewordList) {
        if (rewordList == null || rewordList.size() == 0) {
            null_information_layout.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
            return false;
        } else {
            null_information_layout.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            return true;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = true;
        page = 1;
        httpGetesther_comments_list();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = false;
        page++;
        httpGetesther_comments_list();
    }
}
